package com.zjitc.controller;

import com.zjitc.model.Cart;
import com.zjitc.model.User;
import com.zjitc.service.CartService;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * Create by IntelliJ IDEA
 *
 * @author: jsonor
 * @date-Time: 2018/5/14 16:45
 * @description:
 */
@Controller
@RequestMapping("/cart")
public class CartController {

  @Autowired
  private CartService cartService;

  /**
   * 查询用户购物车
   * @param session
   * @return
   */
  @RequestMapping(value = "/findMyCart")
  public String findMyCart(HttpSession session) {
    User user = (User) session.getAttribute("user");
    if (user ==null){
      return "login";
    }
    List<Cart> list = cartService.findCartByUid(user.getUid());
    session.setAttribute("cart",list);
    return "shopping_cart";
  }

  /**
   * 删除商品
   * @param cartid
   * @param session
   * @return
   */
  @RequestMapping(value = "/deleteCart")
  public String deleteCart(String cartid, HttpSession session){
    cartService.deleteCart(cartid);
    User user = (User) session.getAttribute("user");
    List<Cart> list = cartService.findCartByUid(user.getUid());
    session.setAttribute("cart",list);
    return "shopping_cart";
  }

  /**
   * 添加商品
   * @param pid
   * @param quantity
   * @param session
   * @return
   */
  @RequestMapping(value = "/addCart")
  public String addCart(Integer pid, Integer quantity, HttpSession session){
    User user = (User) session.getAttribute("user");
    if (user == null){
      return "login";
    }
    Cart cart = new Cart();
    cart.setCartid(String.valueOf(UUID.randomUUID()));
    cart.setPid(pid);
    cart.setQuantity(quantity);
    cart.setUid(user.getUid());
    cartService.addCart(cart);
    List<Cart> list = cartService.findCartByUid(user.getUid());
    session.setAttribute("cart",list);
    //金额相加
    Double total = 0.0;
    if (list != null){
      for(Cart i : list){
        total = total+ i.getProduct().getPrice() * i.getQuantity();
      }
      session.setAttribute("total",total);
    }
    return "shopping_cart";
  }

  /**
   * 清空购物车
   * @param session
   * @param uid
   * @return
   */
  @RequestMapping(value = "/cleanCart")
  public String cleanCart(HttpSession session,Integer uid){
    User user= (User) session.getAttribute("user");
    session.removeAttribute("cart");
    uid=user.getUid();
    cartService.cleanCart(uid);
    return "shopping_cart";
  }

}
